<template>
  <a-modal
    class="common-modal"
    :title="title"
    :footer="null"
    :width="500"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    :maskClosable="false"
    style="top: 5%"
  >
    <a-spin :spinning="confirmLoading">
      <a-form
        :model="formState"
        @validateFields="handleOk"
        ref="formRef"
        layout="vertical"
        class="common-modal-content"
      >
        <a-col :span="24">
          <a-form-item :label="$t('deviceManage.waterLineNo')" name="lineNo" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input v-model:value.trim="formState.lineNo" :disabled="true" :placeholder="$t('deviceManage.autoGenerate')"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item :label="$t('deviceManage.waterLineName')" name="name" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input v-model:value.trim="formState.name" :placeholder="$t('deviceManage.pleaseInputWaterLineName')"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item :label="$t('menu.basic:section')" name="sectionId" :labelCol="labelCol" :wrapperCol="wrapperCol" :rules="[{ required: true,  message: $t('basicData.pleaseSelectSection') }]">
            <a-select v-model:value="formState.sectionId" allowClear  :placeholder="$t('common.pleaseSelect')">
              <a-select-option v-for="(item,key) in sectionList" :key="key" :value="item.id">{{item.name}} </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item :label="$t('deviceManage.lineType')" name="lineType" :labelCol="labelCol" :wrapperCol="wrapperCol" :rules="[{ required: true, message: $t('other.pleaseSelectLineType') }]">
            <a-select v-model:value="formState.lineType" allowClear :options="selectOptions.lineTypeArray" :placeholder="$t('common.pleaseSelect')"></a-select>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item :label="$t('deviceManage.workShop')" name="groupId" :labelCol="labelCol"  :wrapperCol="wrapperCol" :rules="[{ required: true, message: $t('other.pleaseSelectWorkSpace') }]">
            <a-select v-model:value="formState.groupId" allowClear :placeholder="$t('common.pleaseSelect')">
              <a-select-option v-for="(item,key) in selectOptions.waGroupList" :key="key" :value="item.id">{{item.name}}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="MAC" name="macAddr" :labelCol="labelCol" :wrapperCol="wrapperCol" :rules="[{ required: true, message: $t('deviceManage.pleaseInputMac')}]">
            <a-auto-complete v-model:value.trim="formState.macAddr" :options="options" :placeholder="$t('deviceManage.pleaseInputMac')" @search="handleSearch"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item :label="$t('common.remark')" :labelCol="labelCol" :wrapperCol="wrapperCol" name="remark">
            <a-textarea v-model:value.trim="formState.remark" />
          </a-form-item>
        </a-col>
      </a-form>
      <div class="common-modal-footer">
        <a-button @click="handleCancel" class="cancel">{{ $t('common.cancel') }}</a-button>
        <a-button @click="handleOk" type="primary" class="confirm">{{ $t('common.cancel') }}</a-button>
      </div>
    </a-spin>
  </a-modal>
</template>

<script setup name="editDialog">
import { nextTick, ref, onMounted, computed } from "vue";
import axios from "@/utils/request";
import { cloneDeep } from "lodash";
import i18n from '@/locales/index'
const { t } = i18n.global
import {store} from "@/store";

const emits = defineEmits(["ok"]);
const labelCol = { span: 23 }
const wrapperCol = { span: 23 }
let title = ref("");
let visible = ref(false);
let isEdit = ref(false);
let confirmLoading = ref(false);
const selectOptions = ref({});
let recordInfo = ref({});
let formState = ref({});
const formRef = ref();
let partNameList = ref([]);
let fileList = ref([]);
let options = ref([]);
let options1 = ref([]);

let sectionList = computed(() => {
  return store.state.normalData.sectionList
})

const handleSearch = async (val) => {
  const optionArr = cloneDeep(options.value);
  let array12 = [];
  array12 = optionArr.filter((item) => item.value.includes(val));
  if (array12.length > 0) {
    options.value = array12;
  } else {
    options.value = options1.value;
  }
};

const edit = async (record, editable) => {
  initModalData(record, editable);
  await nextTick();
  formRef.value.resetFields();
  // 重新查询车间id
  if (record.id) {
    const res = await axios.getAction("/api/device/hanger-line/get", {
      id: record.id,
    });
    if (res.success) {
      record.groupId = res.data.groupId;
    }
  }
  formState.value = cloneDeep(record);
};

const initModalData = (record, editable) => {
  title.value = t('other.editWaterLine')
  let { productPartNameList, sizeNameList, colorNameList, url } = record;
  partNameList.value =
    productPartNameList && productPartNameList.length
      ? productPartNameList.map((item) => ({
          name: item,
          id: Math.random(),
        }))
      : [{ id: Math.random(), name: undefined }];

  record.sizeNameList = sizeNameList || [];
  record.colorNameList = colorNameList || [];
  if (url) fileList.value = [{ uid: "-1", url }];

  recordInfo.value = Object.assign({}, record);
  visible.value = true;
  isEdit.value = editable;
};

const queryParams = (value) => {
  const params = cloneDeep(value);
  params.url = fileList.value.length
    ? fileList.value[0].response
      ? fileList.value[0].response.data
      : fileList.value[0].url
    : null;
  params.id = recordInfo.value.id;
 
}
const handleOk = async () => {
  try {
    const values = await formRef.value.validateFields();
    confirmLoading.value = true;
    const res = await axios.postAction("/api/device/hanger-line/edit", queryParams(values));
    if (res.success) {
      emits("ok");
      confirmLoading.value = false;
      visible.value = false;
    }
  } catch (err) {
    console.log("0000000", err);
  }

  confirmLoading.value = false;
};
const handleCancel = () => {
  visible.value = false;
  initModalStatus();
};

const initModalStatus = () => {
  confirmLoading.value = false;
  formState.value = {};
  formRef.value.resetFields();
  fileList.value = [];
};

const initSelectOptions = (obj) => {
  selectOptions.value = obj;
};

const getOptionList = async () => {
  const res = await axios.getAction("/api/device/hanger-line/get-client-mac");
  res.data &&
    res.data.forEach((item) => {
      options.value.push({ value: item });
      options1.value.push({ value: item });
    });
};

defineExpose({
  edit,
  initSelectOptions,
});
onMounted(() => {
  getOptionList();
  store.dispatch('getSection')
})
</script>